'use client'

import { useState, useEffect } from 'react'
import { useAuth } from '@/contexts/AuthContext'
import { filesAPI } from '@/lib/api'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { FileInfo, FileStats } from '@/lib/types'
import { toast } from 'sonner'
import { safeToast } from '@/lib/utils/safeStateUpdate'

export default function TestPermissionsPage() {
  const { user, isAuthenticated } = useAuth()
  const [files, setFiles] = useState<FileInfo[]>([])
  const [fileStats, setFileStats] = useState<FileStats | null>(null)
  const [isLoading, setIsLoading] = useState(false)
  const [testResults, setTestResults] = useState<any>({})

  const runPermissionTests = async () => {
    if (!isAuthenticated) {
      safeToast(toast.error, '请先登录')
      return
    }

    setIsLoading(true)
    const results: any = {}

    try {
      // 测试1: 获取文件列表
      console.log('🧪 测试1: 获取文件列表')
      const filesResponse = await filesAPI.getFiles()
      results.filesList = {
        success: true,
        count: filesResponse.files?.length || 0,
        message: '成功获取文件列表'
      }
      setFiles(filesResponse.files || [])
    } catch (error: any) {
      results.filesList = {
        success: false,
        error: error.message,
        message: '获取文件列表失败'
      }
    }

    try {
      // 测试2: 获取文件统计
      console.log('🧪 测试2: 获取文件统计')
      const statsResponse = await filesAPI.getFileStats()
      results.fileStats = {
        success: true,
        data: statsResponse,
        message: '成功获取文件统计'
      }
      setFileStats(statsResponse)
    } catch (error: any) {
      results.fileStats = {
        success: false,
        error: error.message,
        message: '获取文件统计失败'
      }
    }

    // 测试3: 权限分析
    console.log('🧪 测试3: 权限分析')
    results.permissionAnalysis = {
      userRole: user?.role,
      isAdmin: user?.role === 'ADMIN',
      canViewAllFiles: user?.role === 'ADMIN',
      canDeleteFiles: user?.role === 'ADMIN' || user?.role === 'EDITOR',
      canUploadFiles: true,
      message: '权限分析完成'
    }

    setTestResults(results)
    setIsLoading(false)
    safeToast(toast.success, '权限测试完成')
  }

  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 Bytes'
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  return (
    <div className="p-6 max-w-6xl mx-auto space-y-6">
      <div className="text-center">
        <h1 className="text-3xl font-bold mb-2">权限测试页面</h1>
        <p className="text-gray-600">测试不同用户角色的权限设置</p>
      </div>

      {/* 用户信息 */}
      <Card>
        <CardHeader>
          <CardTitle>当前用户信息</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div>
              <p className="text-sm text-gray-500">用户名</p>
              <p className="font-medium">{user?.username || '未登录'}</p>
            </div>
            <div>
              <p className="text-sm text-gray-500">角色</p>
              <Badge variant={user?.role === 'ADMIN' ? 'default' : 'secondary'}>
                {user?.role || '未知'}
              </Badge>
            </div>
            <div>
              <p className="text-sm text-gray-500">认证状态</p>
              <Badge variant={isAuthenticated ? 'default' : 'destructive'}>
                {isAuthenticated ? '已认证' : '未认证'}
              </Badge>
            </div>
            <div>
              <p className="text-sm text-gray-500">邮箱</p>
              <p className="font-medium">{user?.email || '无'}</p>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 权限测试 */}
      <Card>
        <CardHeader>
          <CardTitle>权限测试</CardTitle>
        </CardHeader>
        <CardContent>
          <Button 
            onClick={runPermissionTests} 
            disabled={!isAuthenticated || isLoading}
            className="w-full"
          >
            {isLoading ? '测试中...' : '开始权限测试'}
          </Button>
          
          {Object.keys(testResults).length > 0 && (
            <div className="mt-4 space-y-4">
              {Object.entries(testResults).map(([key, result]: [string, any]) => (
                <div key={key} className="p-3 border rounded-lg">
                  <h4 className="font-medium mb-2">{key}</h4>
                  <div className="space-y-2">
                    <p className="text-sm">
                      <span className="font-medium">状态:</span>
                      <Badge variant={result.success !== false ? 'default' : 'destructive'} className="ml-2">
                        {result.success !== false ? '成功' : '失败'}
                      </Badge>
                    </p>
                    <p className="text-sm">
                      <span className="font-medium">消息:</span> {result.message}
                    </p>
                    {result.error && (
                      <p className="text-sm text-red-600">
                        <span className="font-medium">错误:</span> {result.error}
                      </p>
                    )}
                    {result.count !== undefined && (
                      <p className="text-sm">
                        <span className="font-medium">文件数量:</span> {result.count}
                      </p>
                    )}
                    {result.data && (
                      <details className="mt-2">
                        <summary className="cursor-pointer text-sm font-medium">查看数据</summary>
                        <pre className="mt-2 p-2 bg-gray-100 rounded text-xs overflow-auto">
                          {JSON.stringify(result.data, null, 2)}
                        </pre>
                      </details>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* 文件列表 */}
      {files.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>获取到的文件列表</CardTitle>
            <p className="text-sm text-gray-500">
              共 {files.length} 个文件
              {user?.role !== 'ADMIN' && ' (仅显示您上传的文件)'}
            </p>
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              {files.map((file) => (
                <div key={file.id} className="flex items-center justify-between p-3 border rounded">
                  <div>
                    <p className="font-medium">{file.originalName || file.filename}</p>
                    <p className="text-sm text-gray-500">
                      大小: {formatFileSize(file.size)} | 
                      类型: {file.mimeType} | 
                      上传者: {file.uploadedBy.username}
                    </p>
                  </div>
                  <Badge variant="outline">{file.uploadedBy.username}</Badge>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* 文件统计 */}
      {fileStats && (
        <Card>
          <CardHeader>
            <CardTitle>文件统计信息</CardTitle>
            <p className="text-sm text-gray-500">
              统计范围: {fileStats.scope === 'all' ? '全部文件' : '您的文件'}
            </p>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="text-center">
                <p className="text-2xl font-bold">{fileStats.totalFiles}</p>
                <p className="text-sm text-gray-500">总文件数</p>
              </div>
              <div className="text-center">
                <p className="text-2xl font-bold">{formatFileSize(fileStats.totalSize)}</p>
                <p className="text-sm text-gray-500">总大小</p>
              </div>
              <div className="text-center">
                <p className="text-2xl font-bold">{fileStats.filesByType?.length || 0}</p>
                <p className="text-sm text-gray-500">文件类型数</p>
              </div>
              <div className="text-center">
                <p className="text-2xl font-bold">{fileStats.recentFiles?.length || 0}</p>
                <p className="text-sm text-gray-500">最近文件</p>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* 使用说明 */}
      <Card className="bg-blue-50 border-blue-200">
        <CardHeader>
          <CardTitle className="text-blue-800">使用说明</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-2 text-sm text-blue-700">
            <p>1. <strong>登录测试</strong>: 使用不同角色的账户登录，观察权限差异</p>
            <p>2. <strong>权限测试</strong>: 点击"开始权限测试"按钮，检查各项权限</p>
            <p>3. <strong>结果分析</strong>: 查看测试结果，确认权限设置正确</p>
            <p>4. <strong>文件访问</strong>: 验证不同角色用户能看到的文件范围</p>
            <p>5. <strong>统计信息</strong>: 检查统计数据的权限控制</p>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}
